package com.atguigu.sink;

import com.alibaba.fastjson.JSON;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by RUI on 2021/6/10 19:22
 */
public class Es_sink {
    public static void main(String[] args) throws Exception {
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        List<HttpHost> hosts = new ArrayList<>();
        hosts.add(new HttpHost("hadoop162",9200));
        hosts.add(new HttpHost("hadoop163",9200));
        hosts.add(new HttpHost("hadoop164",9200));

        env.fromCollection(waterSensors)
                .addSink(new ElasticsearchSink.Builder<WaterSensor>(
                        hosts,
                        new ElasticsearchSinkFunction<WaterSensor>() {
                            @Override
                            public void process(WaterSensor ws, RuntimeContext rc, RequestIndexer requestIndexer) {

                                IndexRequest source = Requests.indexRequest().index("sensor").type("_doc").id(ws.getId()).source(JSON.toJSONString(ws), XContentType.JSON);

                                requestIndexer.add(source);
                            }
                        }
                ).build());

        env.execute();
    }
}
